package com.zzl.car.controller;

import com.zzl.car.context.ZdpJwtUserContext;
import com.zzl.car.entity.User;
import com.zzl.car.exception.ZdpException;
import com.zzl.car.service.UserService;
import com.zzl.car.util.OssUtil;
import com.zzl.car.util.ZdpImageBase64;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ZdpUserController {

    @Autowired
    private UserService userService;
    @Autowired
    private OssUtil ossUtil;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /*
    * 用户修改个人信息
    * */
    @PostMapping("/updateUser")
    public String updateUser(@RequestBody User user){
        System.out.println(user);
        user.setTelephone(ZdpJwtUserContext.getCurrentName());
        return  userService.updateUserInfo(user);

    }
    /*
    * 用户获取个人信息
    * */
    @GetMapping("/getUser")
    public User getUser(){
        String telephone = ZdpJwtUserContext.getCurrentName();
        User user = userService.getUserInfo(telephone);
        return user;
    }
    /*
    * 邮箱验证验证码
    * */
    @PostMapping("/emailVerify")
    public String emailVerify(@RequestBody Map<String,String> data){
        String email = data.get("email");
        String verify = data.get("verify");
        return userService.emailVerify(email,verify);
    }
    /*
    * 用户上传驾驶证图片
    * */
    @PostMapping("/uploadLicense")
    public String uploadLicense(@RequestParam("files") MultipartFile[] files) throws IOException {

        StringBuffer url = new StringBuffer();
        List<String> message = new ArrayList<>();
        for(int i=0;i<files.length;i++){
            if(i==0){
                url.append(ossUtil.uploadFile(files[i],"UserLicense"));
            }else{
                url.append(";"+ossUtil.uploadFile(files[i],"UserLicense"));
            }
            message.add(ZdpImageBase64.generateBase64(files[i]));
        }
        // update一下
        String telephone = ZdpJwtUserContext.getCurrentName();
        User user =userService.getUserInfo(telephone);
        user.setLicense(url.toString());
        // 表示审核中
        user.setAudit(1);
        // 同时将消息发送给消息队列，让消息队列来进行审核
        Map<String,Object> messageMap = new HashMap<>();
        messageMap.put("images",message);
        messageMap.put("user",user);
        rabbitTemplate.convertAndSend("auditLicense",messageMap);
        // 更新一下用户
        userService.updateUserInfo(user);
        return url.toString();
    }
}
